package utils;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/* 该类控制和数据库的连接 */
public class jdbcUtils {


    private static DataSource dataSource;

    static {


        try {
            Properties properties= new Properties();
            //加载配置文件
            InputStream inputStream=jdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //从流中加载数据
            properties.load(inputStream);
            //创建数据库连接池
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }



    /* 连接数据库
    * @ return 如果返回空值就代表连接失败*/

    public static Connection getConnection(){
        Connection connection=null;
        try {
            connection=dataSource.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }


    /* 关闭连接*/
    public static void close(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
